package com.szhn.aclservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.szhn.aclservice.entity.AclRole;
import com.szhn.aclservice.entity.AclUserRole;
import com.szhn.aclservice.entity.vo.AssignRoleVo;
import com.szhn.aclservice.mapper.AclUserRoleMapper;
import com.szhn.aclservice.service.AclRoleService;
import com.szhn.aclservice.service.AclUserRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szhn.aclservice.service.AclUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author testjava
 * @since 2022-10-28
 */
@Service
public class AclUserRoleServiceImpl extends ServiceImpl<AclUserRoleMapper, AclUserRole> implements AclUserRoleService {

    @Autowired
    private AclRoleService aclRoleService;

    @Autowired
    private AclUserService aclUserService;

    @Override
    public Map<String, Object> getRolesByUserId(String userId) {
        //获取所有角色
        List<AclRole> roles = aclRoleService.list(null);
        //根据用户id查询该用户已经分配的角色
        QueryWrapper<AclUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",userId);
        List<AclUserRole> userRoles = baseMapper.selectList(wrapper);
        ArrayList<String> roleIds = new ArrayList<>();
        for (AclUserRole userRole:userRoles) {
            String roleId = userRole.getRoleId();
            roleIds.add(roleId);
        }

        //返回所有的角色和该用户所拥有的角色id
        HashMap<String, Object> map = new HashMap<>();
        map.put("allRoles",roles);
        map.put("userRoleIds",roleIds);
        return map;
    }

    @Override
    public void doAssign(AssignRoleVo assignRoleVo) {
        //根据用户id删除用户之前分配的角色
        QueryWrapper<AclUserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",assignRoleVo.getUserId());
        baseMapper.delete(wrapper);

        //添加

        String userId = assignRoleVo.getUserId();
        for (String roleId : assignRoleVo.getRoleIds()) {
            AclUserRole aclUserRole = new AclUserRole();
            aclUserRole.setUserId(userId);
            aclUserRole.setRoleId(roleId);
            baseMapper.insert(aclUserRole);
        }
    }
}
